﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using NetSurveillance.WebApp.DataServices;
using NetSurveillance.WebApp.DataServices.Models;
using NetSurveillance.WebApp.Exts;
using NetSurveillance.WebApp.Filters;
using NetSurveillance.WebApp.Foundations;
using NetSurveillance.WebApp.Models;
using NetSurveillance.WebApp.Utilities;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace NetSurveillance.WebApp.Controllers
{
    [WebAppAuthorize]
    public class BaseController : Controller
    {
        public DataProvider DataProvider { get; set; }

        public PersistentDataContainer DataContainer
        {
            get { return PersistentDataContainer.Current; }
        }

        public PersistentDataContainer CacheContainer
        {
            get { return PersistentDataContainer.CurrentCache; }
        }

        public PersistentDataContainer ApplicationContainer
        {
            get { return PersistentDataContainer.CurrentApplication; }
        }

        private User _currentUser;
        private Case _currentCase;
        private Task _currentTask;

        protected User CurrentUser
        {
            get { return _currentUser ?? (_currentUser = DataContainer.Read<User>(PresetValues.SessionKeys.CurrentUser)); }
        }

        protected Case CurrentCase
        {
            get
            {
                if (_currentCase == null)
                {
                    _currentCase = CacheContainer.Read<Case>(PresetValues.ApplicationKeys.CurrentCase);
                    if (_currentCase == null)
                    {
                        _currentCase = DataProvider.CaseService.GetRunningCase();
                        CacheContainer.Add(PresetValues.ApplicationKeys.CurrentCase, _currentCase);
                    }
                }
                return _currentCase;
            }
        }

        protected Task CurrentTask
        {
            get
            {
                if (_currentTask == null)
                {
                    _currentTask =
                        CacheContainer.Read<Task>(PresetValues.ApplicationKeys.CurrentTask);
                    if (_currentTask == null)
                    {
                        _currentTask = DataProvider.TaskService.GetRunningTask();
                        CacheContainer.Add(PresetValues.ApplicationKeys.CurrentTask, _currentTask);
                    }
                }
                return _currentTask;
            }
        }

        protected int PageSize
        {
            get
            {
                var pageSize = ApplicationContainer.Read<int?>(PresetValues.ApplicationKeys.PageSize);
                if (!pageSize.HasValue)
                {
                    var monitorSetting = DataProvider.MonitorSettingService.GetFirstMonitorSetting();
                    if (monitorSetting != null)
                    {
                        if (monitorSetting.DefaultPageSize > 0)
                        {
                            pageSize = monitorSetting.DefaultPageSize;
                            ApplicationContainer.Add(PresetValues.ApplicationKeys.PageSize,
                                                     monitorSetting.DefaultPageSize);
                        }
                        ApplicationContainer.Add(PresetValues.ApplicationKeys.IsShowNoTitleRecord,
                                                 monitorSetting.IsShowTitleRecord);
                    }
                }
                return pageSize.HasValue ? pageSize.Value : PresetValues.DefaultPageSize;
            }
        }

        protected bool IsShowNoTitleRecord
        {
            get
            {
                var isShowNoTitleRecord =
                    ApplicationContainer.Read<bool?>(PresetValues.ApplicationKeys.IsShowNoTitleRecord);
                if (!isShowNoTitleRecord.HasValue)
                {
                    var monitorSetting = DataProvider.MonitorSettingService.GetFirstMonitorSetting();
                    if (monitorSetting != null)
                    {
                        if (monitorSetting.DefaultPageSize > 0)
                        {
                            ApplicationContainer.Add(PresetValues.ApplicationKeys.PageSize,
                                                     monitorSetting.DefaultPageSize);
                        }
                        ApplicationContainer.Add(PresetValues.ApplicationKeys.IsShowNoTitleRecord,
                                                 monitorSetting.IsShowTitleRecord);
                        isShowNoTitleRecord = monitorSetting.IsShowTitleRecord;
                    }
                }
                return !isShowNoTitleRecord.HasValue || isShowNoTitleRecord.Value;
            }
        }

        protected override void Initialize(System.Web.Routing.RequestContext requestContext)
        {
            if (DataProvider == null) DataProvider = new DataProvider(PresetValues.DefaultConnection);
            base.Initialize(requestContext);
        }

        protected virtual JsonNetResult CamelCaseJson(object data)
        {
            return new JsonNetResult {Data = data};
        }

        /// <summary>
        /// 序列化为json格式字符串
        /// </summary>
        /// <param name="value">需要序列化的对象</param>
        /// <param name="formatting">格式化选项（默认值为Formatting.None）</param>
        /// <returns>json格式字符串</returns>
        protected virtual string SerializeObject(object value, Formatting formatting = Formatting.None)
        {
            return JsonConvert.SerializeObject(value, formatting,
                                               new JsonSerializerSettings
                                                   {
                                                       ContractResolver = new CamelCasePropertyNamesContractResolver(),
                                                       NullValueHandling = NullValueHandling.Ignore
                                                   });
        }

        protected virtual void SaveInteractiveTimeout(Interactive ia)
        {
            if (ia == null) return;
            ia.InteractiveStatus = InteractiveStatus.Timeout;
            DataProvider.InteractiveService.Save(ia);
        }
    }
}
